package org.orqlog.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.orqlog.encoder.JSONSerializer;
import org.orqlog.encoder.RpcDecoder;
import org.orqlog.encoder.RpcRequest;
import org.orqlog.handler.UserServerHandler;
import org.orqlog.server.ZkRegister;

import java.util.Date;
import java.util.Random;

public class UserServiceImpl implements UserService {
    protected static String IpPort = null;
    protected static ZkRegister zkRegister = null;

    public UserServiceImpl() {}

    public String methodToCall() throws Exception {
        long start = System.currentTimeMillis();
        System.out.println("methodToCall is invoked!" + new Date());
        if (start % 2 == 0) {
            Thread.sleep(1000);
        } else {
            Thread.sleep(1500);
        }
        long end = System.currentTimeMillis();
        String processTime = (new Date()).getTime() + "," + (end - start);
        // 在zk相应节点更新处理时间
        zkRegister.registerProcessTime(IpPort, processTime);
        return "Call success";
    }

    public String methodToCall(String wd) {
        System.out.println("methodToCall is invoked with " + wd + new Date());
        return "Call success";
    }

    @Override
    public String sayHello(RpcRequest word) {
        System.out.println("调用成功--参数 "+word);
        return "调用成功--参数 "+word;
    }


    //hostName:ip地址  port:端口号
    public static void startServer(String hostName, int port, ZkRegister tZkRegister) throws InterruptedException {
        IpPort = hostName + ":" + port;
        zkRegister = tZkRegister;

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());
                    }
                });
        serverBootstrap.bind(hostName,port).sync();
    }

    /**
     * Update zk responxe time
     */
    {

    }

}
